import React, { useState, useEffect } from 'react';
import { Tag, Space, Dialog, Button, Form, Input } from 'antd-mobile';
import { AddOutline } from 'antd-mobile-icons'
import './index.css';


const TagSelector = ({
  options: propOptions,
  multiple = false,
  onAddOption,
  showAddButton = true,
  ...formItemProps
}) => {
  const [visible, setVisible] = useState(false);
  const [customForm] = Form.useForm();
  const [localOptions, setLocalOptions] = useState(propOptions);
  // 使用 useEffect 监听 propOptions 的变化
  useEffect(() => {
    setLocalOptions(propOptions);
  }, [propOptions]);

  // 渲染内部组件，接收 value 和 onChange
  const InnerTagSelector = ({ value = [], onChange }) => {
    const handleTagClick = (tagValue) => {
      let newValue;
      if (multiple) {
        newValue = value.includes(tagValue)
          ? value.filter((v) => v !== tagValue)
          : [...value, tagValue];
      } else {
        newValue = [tagValue];
      }
      onChange?.(newValue);
    };

    const handleAddCustomTag = async () => {
      try {
        const values = await customForm.validateFields();
        const newOption = {
          label: values.customTag,
          value: values.customTag,
        };

        setLocalOptions(prev => [...prev, newOption]);
        onAddOption?.(newOption);

        const newValue = multiple
          ? [...value, newOption.value]
          : [newOption.value];

        onChange?.(newValue);

        setVisible(false);
        customForm.resetFields();
      } catch (error) {
        console.error('Validation failed:', error);
      }
    };

    return (
      <>
        <Space wrap>
          {localOptions.map(option => (
            <Tag
              key={option.value}
              className={value?.includes(option.value) ? 'custom-tag-selected' : 'custom-tag'}
              onClick={() => handleTagClick(option.value)}
            >
              {option.label}
            </Tag>
          ))}
          {
            showAddButton && (
              <Tag className="custom-tag-add" onClick={() => setVisible(true)}>
                <AddOutline />自定义
              </Tag>
            )
          }
        </Space>

        <Dialog
          visible={visible}
          title={`添加自定义${formItemProps.label}`}
          closeOnMaskClick={true}
          content={
            <Form
              form={customForm}
              footer={
                <Button block type='submit' color='primary' onClick={handleAddCustomTag}>
                  确认
                </Button>
              }
            >
              <Form.Item
                name="customTag"
                label="标签名称"
                help={`字数上限${formItemProps.maxCount}`}
                rules={[{ required: true, message: '请输入标签名称' }]}
              >
                <Input placeholder='请输入' maxLength={formItemProps.maxCount} />
              </Form.Item>
            </Form>
          }
          closeOnAction
          onClose={() => {
            setVisible(false);
            customForm.resetFields();
          }}
        />
      </>
    );
  };

  return (
    <Form.Item {...formItemProps} className='customWrapper'>
      <InnerTagSelector />
    </Form.Item>
  );
};

export default TagSelector;